<?php

class SettingsController extends AppController
{
    # Controller Name to be used
    var $name = 'Settings';

    # Models to be used
    var $uses = array(
        'Group','Status','Priority'
    );

    # set the layout to use
    var $layout = 'admin_layout';

    function  beforeFilter($moduleName = null){
        parent::beforeFilter();
    }

    function index($type = 'get'){

        if ($this->request->is('ajax')) {
            $this->autoRender = false;
            $this->autoLayout = false;
            switch ($type) {
                case 'get' :
                    /**  Get posted data */
                    $page = isset($_POST['page']) ? $_POST['page'] : 1;
                    /** The current page */
                    $sortname = isset($_POST['sortname']) ? $_POST['sortname'] : 'id';
                    /** Sort column */
                    $sortorder = isset($_POST['sortorder']) ? $_POST['sortorder'] : 'desc';
                    /** Sort order */
                    $qtype = isset($_POST['qtype']) ? $_POST['qtype'] : '';
                    /** Search column */
                    $search_query = isset($_POST['query']) ? $_POST['query'] : '';
                    /** Search string */
                    $rp = isset($_POST['rp']) ? $_POST['rp'] : 10;
                    $limit = $rp;
                    $start = ($page - 1) * $rp;

                    $condition_array = array(
                        'Group.deleted' => 'n'
                    );

                    if (!empty($search_query)) {
                        if ($qtype == 'name') {
                            $condition_array = array(
                                'Group.name LIKE ' => $search_query.'%',
                                'Group.deleted' => 'n'
                            );
                        }
                    }

                    $data_table = $this->Group->find('all', array('conditions' => $condition_array, 'order' => "Group.$sortname $sortorder", 'limit' => $start . ',' . $limit, 'recursive' => 1));
                    $data_table_count = $this->Group->find('count', array('conditions' => $condition_array, 'recursive' => -1));

                    $total_records = $data_table_count;

                    if ($data_table) {
                        $return_arr = array();
                        foreach ($data_table as $obj) {
                            $count_mod = count($obj['Module']);
                            $return_arr[] = array(
                                'id' => $obj['Group']['id'],
                                'cell' => array(
                                    $obj['Group']['id'],
                                    $obj['Group']['name'],
                                    $count_mod
                                )
                            );
                        }
                        return json_encode(array('success' => true, 'total' => $total_records, 'page' => $page, 'rows' => $return_arr));
                    }
                    else {
                        return json_encode(array('success' => false, 'total' => $total_records, 'page' => $page, 'rows' => array()));
                    }
                    break;

                case 'save' :
                    $data = array('Group' => $_POST);
                    $pass = '';
                    if ($_POST['id'] > 0) {
                        $data['Group']['modified_by'] = $this->authUser['id'];
                    } else {
                        $data['Group']['created_by'] = $this->authUser['id'];
                    }

                    if ($this->Group->save($data['Group'])) {
                        if($_POST['id'] > 0){
                            return json_encode(array('code' => 0, 'msg' => 'Data Saved'));
                        }
                        else{ //If new pass back extra data if needed.
                            return json_encode(array('code' => 0, 'msg' => 'Data Saved!', 'id'=>$this->Group->id));
                        }
                    } else {
                        echo json_encode(array('code' => 1, 'msg' => 'Some errors occurred.'));
                    }
                    break;

                case 'delete':
                    $ids = $_POST['ids'];
                    $modObj = ClassRegistry::init('Group');
                    $result = $modObj->updateAll(
                        array('Group.deleted' => "'y'",'Group.modified_by' => $this->authUser['id']),
                        array('Group.id' => $ids)
                    );
                    if ($result) {
                        echo json_encode(array('code' => 0, 'msg' => 'Data Deleted!'));
                    } else {
                        echo json_encode(array('code' => 1, 'msg' => 'Data cannot be deleted'));
                    }
                    break;

                case 'sub-load':
                     /** Loading */
                    $gdata = $this->Group->getGroupById($_POST['id']);
                    $return_arr = array();
                    if($gdata){
                        foreach ($gdata['Module'] as $obj) {
                            $return_arr[] = array(
                                'id' => $obj['ModulesGroup']['id'],
                                'cell' => array(
                                    $obj['name']
                                )
                            );
                        }
                        return json_encode(array('code' => 0, 'rows' => $return_arr));
                    }
                    else {
                        return json_encode(array('code' => 1, 'rows' => array(), 'mesg' => __('No Record Found')));
                    }
                break;

                case 'sub-save' :
                    //Validate for new ones
                   // if($_POST['id'] == 0){
                    $res = $this->Group->checkGroupModules($_POST['parent_id'],$_POST['module_id']);
                    if($res){
                        return json_encode(array('code' => 1, 'msg' => 'Record Already Exist.'));
                    }
                   // }
                    $save = array(
                        'ModulesGroup'=>array(
                            'id'=>$_POST['id'],
                            'group_id'=>$_POST['parent_id'],
                            'module_id'=>$_POST['module_id']
                        )
                    );

                    $this->Group->bindModel(array('hasMany' => array('ModulesGroup')));
                    $rest = $this->Group->ModulesGroup->save($save);
                    if ($rest) {
                        if($_POST['id'] > 0){
                            return json_encode(array('code' => 0, 'msg' => 'Data Saved'));
                        }
                        else{ //If new pass back extra data if needed.
                            $new_id = $rest['ModulesGroup']['id'];
                            return json_encode(array('code' => 0, 'msg' => 'Data Saved!', 'id'=>$new_id));
                        }
                    } else {
                        return json_encode(array('code' => 1, 'msg' => 'Some errors occurred.'));
                    }
                    break;

                case 'sub-delete' :
                    $ids = $_POST['ids'];
                    $result = $this->Group->deleteGroupModules($ids);
                    if ($result) {
                        return json_encode(array('code' => 0, 'msg' => 'Data Deleted!'));
                    } else {
                        echo json_encode(array('code' => 1, 'msg' => 'Data cannot be deleted'));
                    }
                break;
            }
        }

        $mods = $this->getModules();
        $modules = array();
        foreach($mods as $mod){
            unset($mod['url']);
            unset($mod['icon']);
            $modules[] = $mod;
        }
        $title_for_layout = 'Groups';
        $page_description = 'Setup And Manage User Groups';
        $this->set(compact('title_for_layout','page_description','modules'));
    }


    function ticket_status($type = 'get'){

        if ($this->request->is('ajax')) {
            $this->autoRender = false;
            $this->autoLayout = false;
            switch ($type) {
                case 'get' :
                    /**  Get posted data */
                    $page = isset($_POST['page']) ? $_POST['page'] : 1;
                    /** The current page */
                    $sortname = isset($_POST['sortname']) ? $_POST['sortname'] : 'id';
                    /** Sort column */
                    $sortorder = isset($_POST['sortorder']) ? $_POST['sortorder'] : 'desc';
                    /** Sort order */
                    $qtype = isset($_POST['qtype']) ? $_POST['qtype'] : '';
                    /** Search column */
                    $search_query = isset($_POST['query']) ? $_POST['query'] : '';
                    /** Search string */
                    $rp = isset($_POST['rp']) ? $_POST['rp'] : 10;
                    $limit = $rp;
                    $start = ($page - 1) * $rp;

                    $condition_array = array(
                        'Status.deleted' => 'n'
                    );

                    if (!empty($search_query)) {
                        if ($qtype == 'name') {
                            $condition_array = array(
                                'Status.name LIKE ' => $search_query.'%',
                                'Status.deleted' => 'n'
                            );
                        }
                    }

                    $data_table = $this->Status->find('all', array('conditions' => $condition_array, 'order' => "Status.$sortname $sortorder", 'limit' => $start . ',' . $limit, 'recursive' => 1));
                    $data_table_count = $this->Status->find('count', array('conditions' => $condition_array, 'recursive' => -1));

                    $total_records = $data_table_count;

                    if ($data_table) {
                        $return_arr = array();
                        foreach ($data_table as $obj) {
                            $set_end = $obj['Status']['set_end'];
                            $d = '';
                            if($set_end == 'Closed'){
                                $d = 'This status will be used to close tickets.';
                            }
                            $return_arr[] = array(
                                'id' => $obj['Status']['id'],
                                'cell' => array(
                                    $obj['Status']['id'],
                                    $obj['Status']['name'],
                                    $d
                                )
                            );
                        }
                        return json_encode(array('success' => true, 'total' => $total_records, 'page' => $page, 'rows' => $return_arr));
                    }
                    else {
                        return json_encode(array('success' => false, 'total' => $total_records, 'page' => $page, 'rows' => array()));
                    }
                    break;

                case 'save' :
                    $data = array('Status' => $_POST);
                    $pass = '';
                    if ($_POST['id'] > 0) {
                        $data['Status']['modified_by'] = $this->authUser['id'];
                    } else {
                        $data['Status']['created_by'] = $this->authUser['id'];
                    }

                    if ($this->Status->save($data['Status'])) {
                        if($_POST['id'] > 0){
                            return json_encode(array('code' => 0, 'msg' => 'Data Saved'));
                        }
                        else{ //If new pass back extra data if needed.
                            return json_encode(array('code' => 0, 'msg' => 'Data Saved!', 'id'=>$this->Status->id));
                        }
                    } else {
                        echo json_encode(array('code' => 1, 'msg' => 'Some errors occurred.'));
                    }
                    break;

                case 'set_closed' :
                    $id = $_POST['id'];
                    $modObj = ClassRegistry::init('Status');
                    $modObj->updateAll(array('Status.set_end' => "''"));
                    $result = $modObj->updateAll(
                        array('Status.set_end' => "'Closed'",'Status.modified_by' => $this->authUser['id']),
                        array('Status.id' => $id)
                    );
                    if ($result) {
                        echo json_encode(array('code' => 0, 'msg' => 'Status updated!'));
                    } else {
                        echo json_encode(array('code' => 1, 'msg' => 'Status cannot be updated'));
                    }
                    break;

                case 'delete':
                    $ids = $_POST['ids'];
                    $modObj = ClassRegistry::init('Status');
                    $result = $modObj->updateAll(
                        array('Status.deleted' => "'y'",'Status.modified_by' => $this->authUser['id']),
                        array('Status.id' => $ids)
                    );
                    if ($result) {
                        echo json_encode(array('code' => 0, 'msg' => 'Data Deleted!'));
                    } else {
                        echo json_encode(array('code' => 1, 'msg' => 'Data cannot be deleted'));
                    }
                break;
            }
        }

        $title_for_layout = 'Ticket Status';
        $page_description = 'Setup And Manage Ticket Status';
        $this->set(compact('title_for_layout','page_description'));
    }


    function ticket_priority($type = 'get'){

        if ($this->request->is('ajax')) {
            $this->autoRender = false;
            $this->autoLayout = false;
            switch ($type) {
                case 'get' :
                    /**  Get posted data */
                    $page = isset($_POST['page']) ? $_POST['page'] : 1;
                    /** The current page */
                    $sortname = isset($_POST['sortname']) ? $_POST['sortname'] : 'id';
                    /** Sort column */
                    $sortorder = isset($_POST['sortorder']) ? $_POST['sortorder'] : 'desc';
                    /** Sort order */
                    $qtype = isset($_POST['qtype']) ? $_POST['qtype'] : '';
                    /** Search column */
                    $search_query = isset($_POST['query']) ? $_POST['query'] : '';
                    /** Search string */
                    $rp = isset($_POST['rp']) ? $_POST['rp'] : 10;
                    $limit = $rp;
                    $start = ($page - 1) * $rp;

                    $condition_array = array(
                        'Priority.deleted' => 'n'
                    );

                    if (!empty($search_query)) {
                        if ($qtype == 'name') {
                            $condition_array = array(
                                'Priority.name LIKE ' => $search_query.'%',
                                'Priority.deleted' => 'n'
                            );
                        }
                    }

                    $data_table = $this->Priority->find('all', array('conditions' => $condition_array, 'order' => "Priority.$sortname $sortorder", 'limit' => $start . ',' . $limit, 'recursive' => 1));
                    $data_table_count = $this->Priority->find('count', array('conditions' => $condition_array, 'recursive' => -1));

                    $total_records = $data_table_count;

                    if ($data_table) {
                        $return_arr = array();
                        foreach ($data_table as $obj) {
                            $return_arr[] = array(
                                'id' => $obj['Priority']['id'],
                                'cell' => array(
                                    $obj['Priority']['id'],
                                    $obj['Priority']['name']
                                )
                            );
                        }
                        return json_encode(array('success' => true, 'total' => $total_records, 'page' => $page, 'rows' => $return_arr));
                    }
                    else {
                        return json_encode(array('success' => false, 'total' => $total_records, 'page' => $page, 'rows' => array()));
                    }
                    break;

                case 'save' :
                    $data = array('Priority' => $_POST);
                    $pass = '';
                    if ($_POST['id'] > 0) {
                        $data['Priority']['modified_by'] = $this->authUser['id'];
                    } else {
                        $data['Priority']['created_by'] = $this->authUser['id'];
                    }

                    if ($this->Priority->save($data['Priority'])) {
                        if($_POST['id'] > 0){
                            return json_encode(array('code' => 0, 'msg' => 'Data Saved'));
                        }
                        else{ //If new pass back extra data if needed.
                            return json_encode(array('code' => 0, 'msg' => 'Data Saved!', 'id'=>$this->Priority->id));
                        }
                    } else {
                        echo json_encode(array('code' => 1, 'msg' => 'Some errors occurred.'));
                    }
                    break;

                case 'delete':
                    $ids = $_POST['ids'];
                    $modObj = ClassRegistry::init('Priority');
                    $result = $modObj->updateAll(
                        array('Priority.deleted' => "'y'",'Priority.modified_by' => $this->authUser['id']),
                        array('Priority.id' => $ids)
                    );
                    if ($result) {
                        echo json_encode(array('code' => 0, 'msg' => 'Data Deleted!'));
                    } else {
                        echo json_encode(array('code' => 1, 'msg' => 'Data cannot be deleted'));
                    }
                    break;
            }
        }

        $title_for_layout = 'Ticket Priorities';
        $page_description = 'Setup And Manage Ticket Priorities';
        $this->set(compact('title_for_layout','page_description'));
    }



    function company(){
        $title_for_layout = 'Company Setup';
        $page_description = 'Setup And Manage Your Company Profile';
        $this->set(compact('title_for_layout','page_description'));
    }
}